/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ConsultaUserDialog.java
 *
 * Created on Aug 23, 2009, 4:12:05 PM
 */
package br.di0.sql.consulta;

import br.di0.nyx.cadastro.CadastroUsuario;
import br.di0.sql.ConexaoPostgres;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import strategy.IDocument;

/**
 *
 * @author di0
 */
public class ConsultaUserDialog extends javax.swing.JDialog {

    /** Creates new form ConsultaUserDialog */
    public ConsultaUserDialog(java.awt.Frame parent, boolean modal, CadastroUsuario caller) {
        super(parent, modal);
        this.caller = caller;
        initComponents();
        atualizaList();

        listSelectionModel = pesquisaTable.getSelectionModel();
        listSelectionModel.addListSelectionListener(
                new SharedListSelectionHandler());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pesquisaPanel = new javax.swing.JPanel();
        pesquisaTextField = new javax.swing.JTextField();
        produtosScrollPane = new javax.swing.JScrollPane();
        pesquisaTable = new javax.swing.JTable();
        nomeLabel = new javax.swing.JLabel();
        comandosPanel = new javax.swing.JPanel();
        okButton = new javax.swing.JButton();
        cancelarButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Usuários");

        pesquisaPanel.setBorder(null);

        pesquisaTextField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                pesquisaTextFieldKeyReleased(evt);
            }
        });

        produtosScrollPane.setName("produtosScrollPane"); // NOI18N

        pesquisaTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Código", "Nome"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        pesquisaTable.setFocusable(false);
        pesquisaTable.setName("pesquisaTable"); // NOI18N
        pesquisaTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        produtosScrollPane.setViewportView(pesquisaTable);
        pesquisaTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        pesquisaTable.getColumnModel().getColumn(0).setResizable(false);
        pesquisaTable.getColumnModel().getColumn(0).setPreferredWidth(55);
        pesquisaTable.getColumnModel().getColumn(1).setResizable(false);
        pesquisaTable.getColumnModel().getColumn(1).setPreferredWidth(255);

        nomeLabel.setText("nome");

        javax.swing.GroupLayout pesquisaPanelLayout = new javax.swing.GroupLayout(pesquisaPanel);
        pesquisaPanel.setLayout(pesquisaPanelLayout);
        pesquisaPanelLayout.setHorizontalGroup(
            pesquisaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pesquisaPanelLayout.createSequentialGroup()
                .addGroup(pesquisaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(pesquisaPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(nomeLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(pesquisaTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 308, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, pesquisaPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(produtosScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 365, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        pesquisaPanelLayout.setVerticalGroup(
            pesquisaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pesquisaPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pesquisaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(pesquisaTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(nomeLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(produtosScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(24, Short.MAX_VALUE))
        );

        comandosPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        comandosPanel.setLayout(new java.awt.GridLayout(1, 0));

        okButton.setMnemonic('S');
        okButton.setText("OK");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });
        comandosPanel.add(okButton);

        cancelarButton.setMnemonic('C');
        cancelarButton.setText("Cancelar");
        cancelarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelarButtonActionPerformed(evt);
            }
        });
        comandosPanel.add(cancelarButton);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pesquisaPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(comandosPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 389, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(pesquisaPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE)
                .addComponent(comandosPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        if (codSelected != null) {
            caller.setCodText(codSelected);
            this.dispose();
        } else {
            JOptionPane.showMessageDialog(null,"Nenhum usuário selecionado",
                    "Usuários", JOptionPane.ERROR_MESSAGE);
        }
}//GEN-LAST:event_okButtonActionPerformed

    private void cancelarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarButtonActionPerformed
        this.dispose();
}//GEN-LAST:event_cancelarButtonActionPerformed

    private void pesquisaTextFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_pesquisaTextFieldKeyReleased
        atualizaList();
    }//GEN-LAST:event_pesquisaTextFieldKeyReleased

    private void atualizaList() {
        String query = "SELECT id_usuario, login FROM usuarios WHERE login ILIKE \'" +
                pesquisaTextField.getText() + "%\' order by login asc";
        ConexaoPostgres postgres = null;
        int index = pesquisaTable.getRowCount();
        for (int i = 0; i < index; i++) {
            ((DefaultTableModel) pesquisaTable.getModel()).removeRow(0);
        }
        try {
            postgres = new ConexaoPostgres();
            Connection conexao = postgres.setConexao();
            Statement stm = conexao.createStatement();
            ResultSet result = stm.executeQuery(query);
            while (result.next()) {
                ((DefaultTableModel) pesquisaTable.getModel()).addRow(new Vector());
                index = pesquisaTable.getModel().getRowCount() - 1;
                pesquisaTable.setValueAt(result.getString("id_usuario"), index, 0);
                pesquisaTable.setValueAt(result.getString("login"), index, 1);
            }
        } catch (SQLException ex) {
            System.out.println("Erro selecionar Usuarios");
            ex.printStackTrace();
        } finally {
            postgres.finalizaConexao();
        }
        /* bd.rs = bd.st.executeQuery("Select" +
        " cod_for,nome_for from fornecedor where nome_for like '" +
        pesquisaTextField.getText() + "%' ");

        while (bd.rs.next()) {
        list.add(bd.rs.getString(1) + " - " + bd.rs.getString(2));
        }
        } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "ERRO " + e.getMessage());
        }*/
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                ConsultaUserDialog dialog = new ConsultaUserDialog(new javax.swing.JFrame(), true, null);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    private void setCodSelected(String cod){
        codSelected = cod;
    }
    
    private CadastroUsuario caller;
    private IDocument doc;
    private String codSelected =  null;
    private ListSelectionModel listSelectionModel;

    class SharedListSelectionHandler implements ListSelectionListener {

        public void valueChanged(ListSelectionEvent e) {
            ListSelectionModel lsm = (ListSelectionModel) e.getSource();

            if (!lsm.isSelectionEmpty()) {
                int minIndex = lsm.getMinSelectionIndex();
                setCodSelected((String) pesquisaTable.getValueAt(minIndex, 0));
            }
            //output.append(newline);
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelarButton;
    private javax.swing.JPanel comandosPanel;
    private javax.swing.JLabel nomeLabel;
    private javax.swing.JButton okButton;
    private javax.swing.JPanel pesquisaPanel;
    private javax.swing.JTable pesquisaTable;
    private javax.swing.JTextField pesquisaTextField;
    private javax.swing.JScrollPane produtosScrollPane;
    // End of variables declaration//GEN-END:variables
}
